<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="!crud.props.searchToggle" >
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="名称">
                <el-input v-model="query.name" placeholder="输入名称搜索"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="通知内容">
                <el-input v-model="query.content" placeholder="输入内容搜索"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="通知标题">
                <el-input v-model="query.title" placeholder="输入标题搜索"/>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="部门">
                <treeselect
                  v-model="query.deptIds"
                  :options="depts"
                  placeholder="选择部门"
                  style="width: 100%"
                  :normalizer="normalizer"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="通知人员">
                <zSelect :value.sync="query.userId" :label="query.userName" url="api/dropDown/sysUserList"/>
              </el-form-item>
            </el-col>
            <el-col style="margin-top: 10px" align="center">
              <rrOperation :crud="crud"/>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="success"
          @click="submitNotice"
          :disabled="crud.selections.length == 0"
          v-permission="permission.notice"
        >通知</el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="danger"
          @click="submitUnNotice"
          :disabled="crud.selections.length === 0"
          v-permission="permission.unNotice"
        >取消通知</el-button>
      </crudOperation>
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="40vm">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="100px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称">
                <el-input v-model="form.name" style="width: 100%"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="类型">
                <el-select v-model="form.type" class="edit-input"  placeholder="请选择单据状态" style="width: 100%">
                  <el-option
                    v-for="(item,index) in dict.t_sys_notice_type"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item  label="通知部门">
                <treeselect :disabled="disabled"
                  multiple
                  v-model="deptIds"
                  :options="depts"
                  placeholder="选择部门"
                  style="width: 100%"
                  :normalizer="normalizer"
                  @select="getDeptsNode"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通知人员">
                <j-select :disabled="disabled" multiple :value.sync="users" style="width: 100%" :showName="userShowName"  url="api/dropDown/sysUserList" @objectList="setUserList"></j-select>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-show="crud.status.add===1">
              <el-form-item label="通知渠道">
                <table-select
                :tableColumns="[{prop:'code',label:'渠道编码',width:'100'},{prop:'name',label:'渠道名称',width: '280'}]" labelKey="name" valueKey="id" :value.sync="form.channelIds" placeholder="请选择渠道" url="/api/dropDown/jstChannelList"  @change="changechannel"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="通知内容">
                <wangEditor style="z-index: 99; position: relative;" v-model="form.content" :isClear="isClear"></wangEditor>
              </el-form-item>
            </el-col>
            <el-col :span="24" >
              <div class="flex flex-row">
                <el-form-item label="图片">
                  <div class="flex flex-row">
                    <div class="demo-image__preview" v-for="item in imageUrl">
                      <el-image
                        style="width: 100px; height: 100px;margin-right: 5px"
                        :src="item"
                        :preview-src-list="[item]">
                      </el-image>
                    </div>
                  </div>
                </el-form-item>
                <el-upload
                  class="upload-demo"
                  :action="upload.url"
                  :show-file-list="false"
                  :headers="upload.headers"
                  :on-success="setUrl"
                >
                  <div class="addImg flex a-item j-content" >+</div>
                </el-upload>
              </div>
            </el-col>
            <el-col :span="5">
              <el-form-item label="通知次数">
                <div>{{ form.noticeCount || 0 }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="5">
              <el-form-item label="是否通知">
                <div>{{ isNotice === 1?'是':'否' }}</div>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input v-model="form.remark" style="width:100%;" />
              </el-form-item>
            </el-col>

          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" stripe border v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler" @row-dblclick="crud.toEdit($event)">
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号"/>
        <!-- <el-table-column v-if="columns.visible('id')" prop="id" label="id" /> -->
        <el-table-column v-if="columns.visible('name')" prop="name" label="名称" width="100"/>
        <el-table-column v-if="columns.visible('type')" prop="type" label="通知类型" width="100">
        <template slot-scope="scope">
          <span>{{ dict.label.t_sys_notice_type[scope.row.type]  }}</span>
        </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('sourceType')" prop="sourceType" label="来源类型" width="100"/>
        <!-- <el-table-column v-if="columns.visible('sourceId')" prop="sourceId" label="来源单据id" /> -->
        <el-table-column v-if="columns.visible('sourceCode')" prop="sourceCode" label="来源单据号" width="100"/>
        <!-- <el-table-column v-if="columns.visible('sourceDetailId')" prop="sourceDetailId" label="来源单据明细id" /> -->
        <el-table-column v-if="columns.visible('deptInfo')" prop="deptInfo" label="通知部门" width="100"/>
        <el-table-column v-if="columns.visible('userInfo')" prop="userInfo" label="通知人员" width="100"/>
        <el-table-column v-if="columns.visible('title')" prop="title" label="通知标题" width="100"/>
        <el-table-column v-if="columns.visible('content')" prop="content" label="通知内容" width="100">
        <template slot-scope="scope">
          <div v-html="scope.row.content"></div>
        </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('noticeCount')" prop="noticeCount" label="通知次数" width="100"/>
        <el-table-column v-if="columns.visible('isNotice')" prop="isNotice" label="是否通知" width="100">
          <template slot-scope="scope">
            <span>{{ dict.label.common_yes_or_no[scope.row.isNotice] }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="columns.visible('remark')" prop="remark" label="备注" width="100"/>
        <!-- <el-table-column v-if="columns.visible('createUserId')" prop="createUserId" label="添加人id" /> -->
        <el-table-column v-if="columns.visible('createUserCode')" prop="createUserCode" label="添加人编码" width="100"/>
        <el-table-column v-if="columns.visible('createUserName')" prop="createUserName" label="添加人名称" width="100"/>
        <el-table-column v-if="columns.visible('createTime')" prop="createTime" label="添加时间" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column v-if="columns.visible('updateUserId')" prop="updateUserId" label="修改人id" /> -->
        <el-table-column v-if="columns.visible('updateUserCode')" prop="updateUserCode" label="修改人编码" width="100"/>
        <el-table-column v-if="columns.visible('updateUserName')" prop="updateUserName" label="修改人名称" width="100"/>
        <el-table-column v-if="columns.visible('updateTime')" prop="updateTime" label="修改时间" width="100">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','sysNotice:edit','sysNotice:del']" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>

  </div>
</template>

<script>
import wangEditor from "@/components/wangEditor";

import crudSysNotice from '@/api/system/sysNotice'
import Treeselect from '@riophae/vue-treeselect'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import {getDepts} from "@/api/system/dept";
import {notice, unNotice}  from '@/api/system/sysNotice'
import jSelect from '@/components/jSelect/jSelect'
import { getToken } from '@/utils/auth'


// crud交由presenter持有
const defaultCrud = CRUD({ title: '通知公告', url: 'api/sysNotice', sort: 'id,desc', crudMethod: { ...crudSysNotice },
  optShow: {
    add: true,
    edit: true,
    del: true
  },})
const defaultForm = {
  id: null, name: null, type: null,
  sourceType: null, sourceId: null,
  sourceCode: null, sourceDetailId: null,
  deptInfo: null, deptIds: null,
  userInfo: null,userIds: null,channelIds:null,
  title: null, content: null, noticeCount: null,
  isNotice: null, remark: null,
  createUserId: null, createUserCode: null,
  createUserName: null, createTime: null,
  updateUserId: null, updateUserCode: null,
  updateUserName: null, updateTime: null }
export default {
  name: 'SysNotice',
  dicts: ['t_sys_notice_type','common_yes_or_no'],
  components: { pagination, crudOperation, rrOperation, udOperation ,Treeselect, jSelect,wangEditor },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  data() {
    return {
      isClear: true,
      permission: {
        add: ['admin', 'sysNotice:add'],
        edit: ['admin', 'sysNotice:edit'],
        del: ['admin', 'sysNotice:del'],
        import: ['admin', 'sysNotice:import'],
        export: ['admin', 'sysNotice:export'],
        copy: ['admin', 'sysNotice:copy'],
        upload: ['admin', 'sysNotice:upload'],
        download: ['admin', 'sysNotice:download'],
        success: ['admin', 'sysNotice:success'],
        danger: ['admin', 'sysNotice:danger'],
      },
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url:'',
        // 上传的文件列表
        fileList: [],
        fileList1: [],
        // 公章图片列表
        stampImgList:[],
        // 门店图片列表
        imageList: []
      },
      imageUrl: [],
      users:'',
      userShowName: '',
      depts:[],
      deptIds:[],
      rules: {
      },
      disabled:false
    }
  },
  watch: {
    'form.id'(n){
      if (!n){
        this.users = []
        this.userShowName = ''
        this.deptIds = []
        this.imageUrl = []
        return
      }
      if (this.form.userInfo != null){
        this.users = JSON.parse(this.form.userInfo).map(item=> item.id)
        this.userShowName = JSON.parse(this.form.userInfo).map(item=>item.name).join(',')
      }
      if (this.form.deptInfo != null){
        this.deptIds = JSON.parse(this.form.deptInfo).map(item=> item.id)
      }else {
        this.deptIds = []
      }
      if (this.form.imageUrl != null){
        this.imageUrl = JSON.parse(this.form.imageUrl)
      }else {
        this.imageUrl = []
      }
    }
  },
  created(){
    this.upload.url = window.location.href.split('/').slice(0,3).join('/')+'/api/common/uploadImage'
    getDepts().then(res=>{
        this.depts = res
    })
  },
  mounted() {
        this.form.content = ""; //设置富文本框默认显示内容
    },
  methods: {
    changechannel(){
      if (this.form.channelIds) {
        this.users=[]
        this.userShowName=''
        this.deptIds=[]
        this.form.userInfo=''
        this.form.deptInfo=''
        this.disabled=true
      }else{
        this.disabled=false
      }
      console.log(this.form.channelIds,'jjjjjjjjjjjjgggggggggg');
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return true
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    },
    submitNotice(){
      const that = this
      notice(this.$refs.table.selection.map(item=>item.id)).then(res=>{
        if(res.status === 200){
          that.$message.success(res.msg)
        }else {
          that.$message.error(res.msg)
        }
        that.crud.refresh()
      })
    },
    submitUnNotice(){
      const that = this
      unNotice(this.$refs.table.selection.map(item=>item.id)).then(res=>{
        if(res.status===200){
          that.$message.success(res.msg)
        }else {
          that.$message.error(res.msg)
        }
        that.crud.refresh()
      })
    },
    setUserList(val){
      this.form.userInfo = JSON.stringify(val)
    },
    getDeptsNode(node){
      this.form.deptInfo = this.getNode(node,'[')
      this.form.deptInfo = this.form.deptInfo.slice(0,-1)+']'
    },
    getNode(node,str){
      if (node.children){
        for (let i =0;i<node.children.length;i++){
          str = this.getNode(node.children[i],str)
        }
      }
      return str+=JSON.stringify({id:node.id,code:node.code,name:node.name})+','
    },
    setUrl(val){

      this.imageUrl.push(val.data.path)
      this.form.imageUrl = JSON.stringify(this.imageUrl)
    },
    normalizer(node) {
      //去掉children=[]的children属性
      if (node.children == null || node.children.length == 0) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
  }
}

</script>

<style lang="scss" scoped>
  .table-img {
    display: inline-block;
    text-align: center;
    background: #ccc;
    color: #fff;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    vertical-align: middle;
    width: 32px;
    height: 32px;
    line-height: 32px;
  }
  .addImg{
    font-size: 60px;
    border: rgb(203,203,203) 1px dashed;
    width: 102px;
    height: 102px;
    cursor: pointer;
    margin-top: 2px;
  }

</style>
